<template>
  <el-dialog title="新建广播" custom-class="gis-broadcast-dialog" :close-on-click-modal="false" :modal="false"
    :visible.sync="open" :before-close="handleClose">
    <el-form ref="form" label-suffix=":" :model="form" size="small" hide-required-asterisk>
      <el-form-item label="广播人员" prop="receiver" class="receiver">
        <el-select v-model="formData.receiver" multiple disabled class="receiver-select" style="width:100%">
        </el-select>
      </el-form-item>
      <el-form-item class="flex" label="广播模式" prop="callMode">
        <el-radio-group v-model="form.callMode">
          <el-radio label="manual">人工语音</el-radio>
          <el-radio label="tts">文字</el-radio>
          <el-radio label="file">文件</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="callMode !== 0" class="flex" label="播放模式" prop="timeRadio">
        <el-radio-group v-model="timeRadio" @change="changetime">
          <el-radio :label="-1">循环</el-radio>
          <el-radio :label="1">播放次数
            <el-input-number v-if="timeRadio === 1" v-model="form.time" :min="1" :controls="false">
            </el-input-number>
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item class="flex" label="追呼次数" prop="callLoop">
        <el-radio-group v-model="callLoop" @change="changeLoop">
          <el-radio :label="-1">循环</el-radio>
          <el-radio :label="0">不追呼</el-radio>
          <el-radio :label="1">追呼次数
            <el-input-number v-if="callLoop === 1" v-model="form.callLoop" :min="1" :controls="false">
            </el-input-number>
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="广播内容" prop="content" v-if="form.callMode==='tts'">
        <el-input type="textarea" :rows="5" resize="none" placeholder="" v-model="content" />
      </el-form-item>
      <el-form-item label="语音文件" prop="content" v-else-if="form.callMode==='file'">
        <img class="upload-img" src="@/assets/images/Add.png" @click="selectFile(true)" v-show="!form.fileName" />
        <div v-show="form.fileName" class="file-list">
          <span>{{form.realFileName}}</span>
          <i class="el-icon-circle-close" @click="deleteFile"></i>
        </div>
      </el-form-item>
    </el-form>

    <el-divider class="default-divider"></el-divider>

    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handleCommit">确 定</el-button>
    </span>

    <!-- 广播文件 -->
    <el-dialog title="选择广播文件" :visible.sync="openFile" :modal="false" :close-on-click-modal="false"
      custom-class="broadcast-dialog" :before-close="handleSelectClose">
      <svg-icon class="back-to-list" icon-class="back" @click="openFile = false"></svg-icon>
      <el-input placeholder="请输入文件名称" v-model="searchKey" class="search-input" size="small" autocomplete
        @blur="filterData">
        <i slot="prefix" class="el-input__icon el-icon-search"></i>
      </el-input>
      <el-table ref="filterTable" :data="filterData()" height="calc(100% - 3.5vw)" :highlight-current-row="true"
        v-loading="uploading" element-loading-background='#1a4969' :element-loading-text="loadingText"
        @current-change="currentRowChange" @row-dblclick="rowDblclick" cell-class-name="table-cell-custom"
        header-cell-class-name="table-herder-custom" size="small" @selection-change="selectionChange">
        <el-table-column width="100" type="selection" align="center"></el-table-column>
        <el-table-column prop="orifilename" show-overflow-tooltip label="文件名称"></el-table-column>
        <!-- <el-table-column prop="filesize"
                       label="文件大小(KB)"
                       width="180"></el-table-column> -->
        <!-- <el-table-column prop="remark" label="备注"></el-table-column> -->
        <el-table-column align="center">
          <template slot-scope="scope">
            <el-link @click.stop="handleDelete(scope.row)">删除</el-link>
            <!-- <el-link icon="el-icon-headset" @click="handleTrail(scope.row)">试听</el-link>
            <el-link icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-link> -->
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-upload ref="upload-file" :accept="accept" auto-upload :show-file-list="false" :action="uploadUrl()"
          :headers="uploadHeaders" :on-success="onSuccess" style="display:none">
          <img src="@/assets/images/Add.png" id="upload" />
        </el-upload>
        <el-button @click="handleUpload()" size="small">上 传</el-button>
        <el-button @click="handleDelete()" :disabled='checkedRows.length === 0' size="small">删 除</el-button>
        <el-button @click="handleSelect()" :disabled='checkedRows.length !== 1' size="small">确 定</el-button>
      </div>

    </el-dialog>

  </el-dialog>
</template>

<script>
import axios from 'axios'
import { msgWarning, msgError, msgSuccess } from '@/utils/message'
import { mapGetters } from 'vuex'
export default {
  props: {
    open: Boolean,
    formData: Object,
  },

  data() {
    return {
      uploadHeaders: {
        ContentType: 'multipart/form-data',
        Authorization: sessionStorage.getItem('tokenSign'),
        FileType: 'filebroadcast',
      },
      accept: '.wav,.mp3,.au',

      form: {
        callMode: 'manual', // 广播类型
        callLoop: 0, // 追呼次数
        fileName: '', // 语音文件
        time: -1, // 播放次数
      },

      callLoop: 0, // 追呼次数
      timeRadio: -1, // 播放次数选择
      content: '', // 文字内容

      openFile: false,

      tableData: [], // 文件列表
      searchKey: '',
      checkedRows: [], // 选择文件列表
      currentRow: null,

      uploading: false,
      loadingText: '',
    }
  },
  computed: {
    ...mapGetters(['operatorInfo', 'operatorCallTels', 'deviceStatusMap']),
  },
  methods: {
    onProgress(event, file, fileList) {
      console.log('onProgress', event.percent, file, fileList)
      this.loadingText = `文件上传进度 ${event.percent.toFixed(3)}%`
      this.percentage = event.percent
    },
    beforeUpload() {
      this.uploading = true
    },
    onError() {
      this.uploading = false
      this.loadingText = ''
      msgError('文件上传失败')
      this.deleteFile()
    },
    // 改变播放值
    changetime(val) {
      this.form.time = val
    },
    // 改变追呼值
    changeLoop(val) {
      this.form.callLoop = val
    },
    // 获取文件上传url
    uploadUrl() {
      return SDK.idispatchServer() + '/fileflow'
    },
    // 选择文件列表
    selectFile(open) {
      SDK.voiceFileList()
        .then((res) => {
          this.tableData = res.VoiceFileList
          if (open) {
            this.currentRow = null
            this.checkedRows = []
            this.openFile = true
          }
        })
        .catch(() => {
          msgError('获取文件列表失败')
        })
    },
    // 删除文件
    deleteFile() {
      this.form.fileName = ''
      this.form.realFileName = ''
      this.$refs['upload-file'].clearFiles()
    },
    // 生成tts文件
    async genarateTts() {
      await SDK.genarateTts(this.content)
        .then((res) => {
          this.form.fileName = res.filename
        })
        .catch((err) => {
          console.log('文字转tts语音失败', err)
          this.form.fileName = ''
          msgError('文字转tts语音失败')
        })
    },
    // 上传按钮
    handleUpload() {
      document.getElementById('upload').click()
    },
    // 文件上传成功
    onSuccess(response, file) {
      this.uploading = false
      console.log('onSuccess', response, file)
      if (response.msg === 'success') {
        this.selectFile()
        msgSuccess('上传文件成功')
        return
      } else {
        msgError('上传文件失败')
      }
      this.deleteFile()
    },
    // 删除按钮
    handleDelete(row) {
      let rows = row ? [row] : this.checkedRows
      if (rows.length === 0) {
        msgError('请至少选择一项')
        return
      }
      const self = this
      this.$confirm('确定要删除选中项吗？', '提示', {
        customClass: 'custom-message-box',
        distinguishCancelAndClose: true,
        showClose: false,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(async () => {
          let errors = []
          for (let i = 0; i < rows.length; i++) {
            await SDK.deleteFile(rows[i].fileid)
              .then((res) => {
                console.log('res', res)
              })
              .catch(() => {
                errors.push(rows[i].orifilename)
              })
          }
          if (errors.length > 0) {
            msgError(errors.join(',') + ' 删除失败')
          } else {
            msgSuccess('删除文件成功')
          }
          setTimeout(() => {
            self.selectFile()
          }, 200)
        })
        .catch(() => {})
    },
    // 选中文件
    handleSelect() {
      let file =
        this.currentRow ||
        (this.checkedRows.length === 1 ? this.checkedRows[0] : null)
      if (!file) {
        msgError('只能选择一个文件')
        return
      }
      this.form.fileName = file.filename
      this.form.realFileName = file.orifilename
      this.handleSelectClose()
    },
    // 对数据进行过滤
    filterData() {
      if (!this.searchKey) return this.tableData
      return this.tableData.filter((data) =>
        data.orifilename.toLowerCase().includes(this.searchKey.toLowerCase())
      )
    },
    // 高亮行变化
    currentRowChange(currentRow) {
      this.currentRow = currentRow
    },
    // 选择框改变是触发
    selectionChange(rows) {
      this.checkedRows = rows
    },
    // 双击表格
    rowDblclick(file) {
      this.form.fileName = file.filename
      this.form.realFileName = file.orifilename
      this.handleSelectClose()
    },
    //发送短信
    async handleCommit() {
      if (!this.form.callMode === 'tts' && !this.content) {
        msgError('请输入文字内容')
        return
      }
      if (!this.form.callMode === 'file' && !this.form.fileName) {
        msgError('请添加语音文件')
        return
      }
      if (this.form.callMode === 'manual') {
        if (this.formData.contacts.has(this.operatorInfo.operatorID)) {
          this.formData.contacts.delete(this.operatorInfo.operatorID)
        }
        let callingDevice = this.operatorCallTels.find((item) => {
          let status = this.deviceStatusMap.get(item)
          return status === 'offline' ? false : true
        })
        if (!callingDevice) {
          msgError('操作员手柄不在线')
          return
        }
        this.form.callingDevice = callingDevice
        this.$store.commit('callFlagEvent', true) // vuex缓存
      } else if (this.form.callMode === 'tts') {
        await this.genarateTts()
        if (!this.form.fileName) return
      }
      this.form.called = [...this.formData.contacts.values()]

      SDK.broadcastCall(this.form) // 提交表单
        .then((res) => {
          this.handleClose()
        })
        .catch((err) => {
          console.log(err)
          this.$store.commit('callFlagEvent', false) // vuex缓存
        })
    },
    // 关闭或取消
    handleClose() {
      this.$emit('update:open', false)
    },
    // 关闭文件选择
    handleSelectClose() {
      this.openFile = false
    },
  },
}
</script>

<style lang="scss" scoped>
@import '~@/assets/scss/gis_broadcast_dialog.scss';
</style>


